package com.itheima.web.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.service.front.ExamQuestionService;
import com.itheima.service.front.MemberService;
import com.itheima.service.front.impl.ExamQuestionServiceImpl;
import com.itheima.service.front.impl.MemberServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @program: mm
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-12 16:17
 **/
public class BaseServlet extends HttpServlet {
    protected MemberService memberService;
    protected ExamQuestionService examQuestionService;

    @Override
    public void init() throws ServletException {
        memberService = new MemberServiceImpl();
        examQuestionService = new ExamQuestionServiceImpl();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        // /system/login

        int index = uri.lastIndexOf("/");

        String methodName = uri.substring(index + 1);

        //
        try {
            Method method = this.getClass().getDeclaredMethod(methodName,
                    HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);
            Result result = (Result) method.invoke(this, req, resp);
            //通过反射来,等下改造 通过json来传递,不是通过序列化
            resp.setContentType("application/json;charset=utf-8");
            ServletOutputStream os = resp.getOutputStream();
            JSON.writeJSONString(os, result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }
}
